/*
 * @lc app=leetcode.cn id=106 lang=java
 *
 * [106] 从中序与后序遍历序列构造二叉树
 */

// @lc code=start
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
import java.util.HashMap;
import java.util.Map;
class Solution {

    Map<Integer, Integer> inorderIndexMap = new HashMap<>();
    int[] post;
    public TreeNode buildTree(int[] inorder, int[] postorder) {
        for(int i = 0; i < inorder.length; i++) {
            inorderIndexMap.put(inorder[i], i);
        }
        post = postorder;
        TreeNode root = buildTreeFun(0, inorder.length - 1, 0, postorder.length - 1);
        return root;

    }

    private TreeNode buildTreeFun(int inorderStart, inorderEnd, int postorderStart, postorderEnd) {
        if(inorderStart > inorderEnd || postorderStart > postorderEnd) {
            return null;
        }

        int root = postorder[postorderEnd];
        int inorderIndex = inorderIndexMap.get(root);

        TreeNode node = new TreeNode(root);

        root.left = buildTree(inorderStart, inorderIndex - 1, postorderStart, postorderStart + inorderIndex - inorderStart - 1);
        root.right = buildTree(inorderIndex + 1, inorderEnd, postorderStart + inorderIndex-inorderStart, postorderEnd - 1);

        return node;
    }
}
    // @lc code=end

